import 'dart:convert';

import 'package:basic_core/storage/local_storage.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../models/user.dart';

class AuthRepository {
  User? _currentUser;

  User? get currentUser => _currentUser;

  Stream<User?> authStateChanges() async* {
    // 你可以根据需求实现监听用户状态变化的逻辑
    // 尝试从本地存储加载当前用户信息
    final prefs = await SharedPreferences.getInstance();
    final userJson = prefs.getString('currentUser');
    if (userJson != null) {
      _currentUser = User.fromJson(jsonDecode(userJson));
    }
    yield _currentUser;
  }

  Future<bool> login(User user) async {
    // 模拟网络请求，通常会调用 API
    await Future.delayed(const Duration(seconds: 2)); // 模拟延迟
    // 假设我们总是成功登录，返回一个 mock 用户
    final mockUser = User(
      uid: 'mock-uid-12345',
      email: user.email,
      displayName: 'Mock User',
      createdAt: DateTime.now(),
      lastLoginAt: DateTime.now(),
    );

    // 将 mock 用户转化为 JSON
    final userJson = jsonEncode(mockUser.toJson());

    final prefs = await SharedPreferences.getInstance();
    final localStorage = LocalStorage(prefs);
    localStorage.setString('currentUser', userJson);

    // 模拟成功的返回
    _currentUser = mockUser;
    return user.email == "test" || user.phone == "1234567890"; // 简单验证
  }

  Future<bool> register(User user) async {
    // 模拟注册逻辑
    await Future.delayed(const Duration(seconds: 2)); // 模拟延迟
    return true;
  }
}

final authRepositoryProvider = Provider((ref) => AuthRepository());
